/**
 * Created by chenweicheng on 8/3/2017.
 */
/**
 * Created by Administrator on 2016/12/20 0020.
 */

import React, {Component} from 'react';
import {
    AppRegistry, View, Text, ScrollView, Image, StyleSheet, TouchableHighlight, Platform,
    PermissionsAndroid, NativeAppEventEmitter, NativeEventEmitter, NativeModules
} from 'react-native';

var NativeManager = NativeModules.BleManager;
const myNativeEvt = new NativeEventEmitter(NativeManager);
var emiter = Platform.OS === 'android' ? NativeAppEventEmitter : myNativeEvt;

import BleManager from '../BleManager';
import ProtobufJsManager from '../ProtobufJsManager';

export default class TestProtoManager extends Component {

    constructor(props) {
        super(props);
        this.state = {
            ble: null,
            connectState: 'disconnected',
        };
        this.scanning = false;
        this.root = null;
    }


    sendEvent() {
        BleManager.sendEvent("BleManagerDidUpdateValueForCharacteristic", {
            peripheral: 'peripheral000',
            characteristic: 'SADWQEQWD',
            rawstr: 'RAW DATA'
        })
    }


    test_Proto() {

        //创建一个ToothbrushMessage消息
        let ToothbrushMessage = ProtobufJsManager.getProtoMessage(ProtobufJsManager.headerType.ToothbrushMessage);
        //根据实际情况set
        let message = ToothbrushMessage.create({LoopCount: ProtobufJsManager.getLoopCount(), BindId: 1});

        //生成一个ToothbrushMessage消息





        ProtobufJsManager.createMessage(message, ProtobufJsManager.headerType.ToothbrushMessage).then((createMsg) => {
            //生成的消息
            console.log("create message success:" + createMsg);

            //获取messageid，messageid即为消息类型
            ProtobufJsManager.getMessageId(createMsg);

            //解析收到的消息
            let parseResult = ProtobufJsManager.parseMessage(createMsg);
            console.log("解析结果：" + parseResult);
            console.log("解析结果：" + parseResult.LoopCount)

        }, (error) => {
            console.log("create message fail:" + error)
        });
    }


    componentDidMount() {


        BleManager.start({showAlert: true}).then(() => {
            console.log("start successss:");
            //检查蓝牙开关
            BleManager.checkState();
        }, (error) => {
            console.log("start fail" + error);
        });
        this.handleDiscoverPeripheral = emiter
            .addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral.bind(this));
        //连接设备成功广播
        this.handleConnectedPeripheral = emiter
            .addListener('BleManagerConnectPeripheral', this.handleConnectedPeripheral.bind(this));
        //断开连接成功广播
        this.handleDisConnectedPeripheral = emiter
            .addListener('BleManagerDisconnectPeripheral', this.handleDisConnectedPeripheral.bind(this));
        //收到数据广播
        this.handleNotification = emiter
            .addListener('BleManagerDidUpdateValueForCharacteristic', this.handleNotification.bind(this));
        this.handleBleManagerDidUpdateState = emiter
            .addListener('BleManagerDidUpdateState', this.handleBleManagerDidUpdateState.bind(this));


        if (Platform.OS === 'android' && Platform.Version >= 23) {
            PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
                if (result) {
                    console.log("Permission is OK");
                } else {
                    PermissionsAndroid.requestPermission(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
                        if (result) {
                            console.log("User accept");
                        } else {
                            console.log("User refuse");
                        }
                    });
                }
            });
        }
        this.startScan(true)


    }

    static componentWillUnmount() {
        //反注册广播
        NativeAppEventEmitter.removeAllListeners();
    }

    handleConnect(data) {

        BleManager.connect(data['id']).then((map) => {
            this.handleStartNotification(this.state.ble);
        }, (error) => {
            console.log("connect fail");
            console.log(error);

        });
    }

    handleStartNotification(data) {
        BleManager.setNotification(data['id']).then(
            () => {
                console.log('start notification success')
            },
            (error) => {
                console.log('start notification fail', error)
            });
    }

    handleDiscoverPeripheral(data) {
        if (data['name'] == null) {

        } else {
            var name = data['name'];
            var fdStart = name.indexOf("ToothBrush");
            if (fdStart == 0) {
                // 表示strCode是以ssss开头；
                clearInterval(this.scanId);
                this.scanning = false;
                this.setState({ble: data});
                this.handleConnect(this.state.ble)
            } else if (fdStart == -1) {
                //  表示strCode不是以ssss开头
                console.log('handleDiscoverPeripheral')

            }
        }
    }

    handleConnectedPeripheral(data) {
        this.setState({connectState: 'connected'});
    }

    handleDisConnectedPeripheral(data) {
        this.setState({connectState: 'disconnected'});
        this.startScan(true);
        // alert('糟糕，断开了')
    }

    handleNotification(data) {
        console.log('handleNotification', data);
    }

    handleBleManagerDidUpdateState(data) {
        if (data['state'] == "on") {
        } else if (data['state'] == "off") {
            this.setState({connectState: 'disconnected'});
            BleManager.enableBluetooth().then(() => {
                console.log('BLE 开关打开成功',);
            }, (result) => {
                console.log('BLE 开关打开失败', result);
            });
        }

    }

    startScan(bool) {
        if (bool) {
            this.scanning = true;
            this.scanId = setInterval(() => this.handleScan(), 5000);
        } else {
            this.scanning = false;
            clearInterval(this.scanId);
            BleManager.stopScan().then(() => {
                console.log('stop scan success')
            }, (error) => {
                console.log('stop scan fail')
            })

        }
    }

    handleScan() {
        BleManager.scan(3, 'ToothBrush')
            .then(() => {
                //  console.log('Scanning.Success..')
            }, (error) => {
                //    console.log('Scanning...fail')
            });
    }

    handleWriteBack(ble, data) {


        BleManager.writeBack(ble['id'], data).then((map) => {
            console.log("handleWriteBack..success");
            console.log(map)
        }, (error) => {
            console.log("handleWriteBack..fail");
            console.log(error)
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight style={{padding: 20, backgroundColor: '#ccc'}}
                                    onPress={() =>this.sendEvent()  }>
                    <Text>send event</Text>
                </TouchableHighlight>
                <TouchableHighlight style={{padding: 20, backgroundColor: '#ccc'}}
                                    onPress={() =>this.test_Proto()  }>
                    <Text>Protobufjs_decodeio</Text>
                </TouchableHighlight>
                <TouchableHighlight style={{padding: 20, backgroundColor: '#ccc'}}
                                    onPress={() =>this.test_Proto2()  }>
                    <Text>protobuf_google</Text>
                </TouchableHighlight>

                <TouchableHighlight style={{padding: 20, backgroundColor: '#ccc'}}
                                    onPress={() =>this.handleWriteBack(this.state.ble,'aac8b0a318593647fd24d6')  }>
                    <Text>handleWriteBack</Text>
                </TouchableHighlight>
            </View>
        );
    }
}
//aac8b0a318593647fd24d6  ///aac8b0a718593647fd2422
var styles = StyleSheet.create({
    container: {
        //   justifyContent: 'center',
        flex: 1,
        flexDirection: 'column',//没有flexDirection这个属性的话，justifyContent不会生效
        justifyContent: 'center',
        padding: 15,
        alignItems: 'center'
    }
});
AppRegistry.registerComponent('TestProtoManager', () => TestProtoManager);